import ast

import requests

import pandas as pd
import base64
import json
import os
import shutil
import time
import random
from collections import OrderedDict
from urllib.parse import quote_plus
import redis
import requests
from sqlalchemy import create_engine
from DrissionPage import ChromiumPage
from DrissionPage import ChromiumOptions
from DrissionPage.common import Settings
from DrissionPage.common import Keys
from DrissionPage.common import Actions
import pymysql
from DrissionPage.errors import *

import datetime


"""
https://customer.xiaohongshu.com/api/cas/customer/web/qr-code?service=https:%2F%2Fcreator.xiaohongshu.com&qr_code_id=68c517395516719772176435"""

class DOUYIN_LIFE:
    def __init__(self,user_id):
        self.CO = ChromiumOptions()  ##创建chrome实例
        # self.user_id = self.user_input()  ##用户
        self.user_id = str(user_id)  ##用户

        self.PORT = self.port_input()  ##chrome端口
        self.CO.set_paths(browser_path="browser_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")  ##chrome启动路径
        self.CO.set_local_port(self.PORT)  ##生成的端口 这里是手动生成
        self.CO.set_user_data_path(os.getcwd() + '/user_info_dir/{}'.format(self.user_id))  ##用户chrome文件夹
        # self.CO.arguments.append('--headless')
        self.ch = ChromiumPage(self.CO)


        self.ch.set.window.max()  ##chrome窗口最大化
        self.ac = Actions(self.ch)
        # self.fans = self.xhs_user_info_requests()
        # print(self.user_id)
        # self.redis_conn = redis.StrictRedis(host='r-bp162522qrwjh5e7jhpd.redis.rds.aliyuncs.com', port=6379,
        #                                     password='123sdmmh568%$#vs*!', db=21)
        self.redis_conn = redis.StrictRedis(host='r-bp1y4wxs1fa8vxd1xspd.redis.rds.aliyuncs.com', port=6379,
                                            password='Jison0820', db=0)

    """根据用户ID查出端口号"""

    def port_fe(self):
        sql = "select spider_user_id,spider_port,spider_login_code from dy_life_center where spider_user_id='{}'".format(
            self.user_id)
        spider_config = self.pymysql_fetchall(sql)
        port = []
        for i in spider_config:
            port.append(i[1])

        return ''.join(port)

    """自动输入端口号"""

    def port_input(self):

        port1 = random.randint(5000, 9000)

        cc = self.port_jiance()
        while True:
            cc = self.port_jiance()
            if cc == "用户存在":
                # print("当前用户存在")
                port_ = self.port_fe()
                # print(port_)
                return port_
            if cc == "端口不存在":
                # print(port1)
                return port1
            else:
                return self.PORT

    """自动随机生成端口 并进行检测"""

    def port_jiance(self):
        port1 = random.randint(5000, 9000)

        sql = "select spider_user_id,spider_port,spider_login_code from dy_life_center"
        spider_config = self.pymysql_fetchall(sql)
        port_list = []
        # print(spider_config)
        for i in spider_config:
            port_list.append(i[1])
        user_exists = self.user_state()
        # print(user_exists, '************')
        if user_exists == "用户不存在":
            if port1 not in port_list:
                return "端口不存在"
            else:
                return "端口存在"
        else:
            return '用户存在'

    """查询数据库"""

    def pymysql_fetchall(self, sql):

        con = pymysql.connect(host='rm-bp1be6s3581xp13rfco.mysql.rds.aliyuncs.com', port=3306, user='root',
                              passwd='Jison0820', db='data-warehouse', charset='utf8')
        # 获取操作数据的对象 cursor
        cursor = con.cursor()
        cursor.execute(sql)
        sql_result = cursor.fetchall()
        # 提交事务
        con.commit()
        # 关闭Cursor
        cursor.close()
        # 关闭链接
        con.close()

        return sql_result

    """从数据库判断用户是否存在"""

    def user_state(self):
        sql = "select spider_user_id,spider_port,spider_login_code from dy_life_center"
        result = self.pymysql_fetchall(sql)
        user_list = []
        for i in result:
            user_list.append(i[0])
        # print(user_list)
        if self.user_id in user_list:
            # print("存在")
            return "用户存在"
        else:
            return "用户不存在"

    """判断用户是否在数据库中 不在为新用户 在的话为老用户"""

    def user_info(self):
        engine2 = self.mysql_config()
        data_frame = pd.DataFrame([{"spider_user_id": str(self.user_id), "spider_port": str(self.PORT)}])
        # print(data_frame)
        # pd.io.sql.to_sql(data_frame, 'xhs_user_info', engine2, schema='live_data',if_exists='append',index=False)
        return data_frame


    # def mysql_config(self):
    #     user = 'live_data'
    #     password = quote_plus('CJMg2tsHg7sj6bo0UTKq0a4T!fPDpJ')
    #     # passwd ='merchantsasd123!@%&'
    #     host = 'rm-bp17r99475xuauk63yo.mysql.rds.aliyuncs.com'
    #     # port1 ='3306'
    #     dbname2 = 'live_data'
    #     engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
    #     return engine2


    def mysql_config(self):
        user = 'root'
        password = quote_plus('Jison0820')
        # passwd ='merchantsasd123!@%&'
        host = 'rm-bp1be6s3581xp13rfco.mysql.rds.aliyuncs.com'
        # port1 ='3306'
        dbname2 = 'data-warehouse'
        engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
        return engine2


    """修改用户登录状态的mysql"""

    def pymysql_update(self, sql, num):

        con = pymysql.connect(host='rm-bp1be6s3581xp13rfco.mysql.rds.aliyuncs.com', port=3306, user='root',
                              passwd='Jison0820', db='data-warehouse', charset='utf8')
        # 获取操作数据的对象 cursor
        cursor = con.cursor()
        cursor.execute(sql, (num, self.user_id))
        # sql_result = cursor.fetchall()
        # 提交事务
        con.commit()
        # 关闭Cursor
        cursor.close()
        # 关闭链接
        con.close()

        return "用户{}状态修改成功,当前状态值为{}".format(self.user_id, num)

    """修改用户三十天数据"""
    def pymysql_update_total(self, sql):

        con = pymysql.connect(host='rm-bp17r99475xuauk63yo.mysql.rds.aliyuncs.com', port=3306, user='root',
                              passwd='CJMg2tsHg7sj6bo0UTKq0a4T!fPDpJ', db='data-warehouse', charset='utf8mb4')
        # 获取操作数据的对象 cursor
        cursor = con.cursor()
        cursor.execute(sql,)
        # sql_result = cursor.fetchall()
        # 提交事务
        con.commit()
        # 关闭Cursor
        cursor.close()
        # 关闭链接
        con.close()

        return "用户{}值成功,当前状态值".format(self.user_id)


    """获取cookies"""
    def get_cookies(self):
        cookies_str = ''
        for i in self.ch.cookies(all_domains=False, all_info=True):
            my_ordered_dict = OrderedDict(i)

            # 取出前两个键值对
            first_two_items = list(my_ordered_dict.items())[:2]
            key_value_str = ''
            count_key_value = 0
            for i in first_two_items:
                count_key_value = count_key_value + 1
                if count_key_value == 1:
                    key_value_str = key_value_str + i[1] + '='
                else:
                    key_value_str = key_value_str + i[1]
            cookies_str = cookies_str + key_value_str + ";"
        return cookies_str



    def listen_shop_name_list(self):
        self.ch.refresh()
        self.ch.listen.start('https://life.douyin.com/life/gate/v1/account/groupAccountList/?page_index=1&page_size=20&name=')


        shop_name_index = []
        life_account_id_list = []
        shop_name = '上海明牌首饰有限公司'
        for packet in self.ch.listen.steps(timeout=3):
            account_list = packet.response.body["data"]["list"]
            life_account_id = account_list[0]["detail"]["life_account_id"]
            life_account_id_list.append(life_account_id)
            # 使用 enumerate 遍历列表并查找索引
            for index, item in enumerate(account_list):
                if item['account_name'] == shop_name:
                    shop_name_index.append(index)
                    break  # 找到后退出循环
            else:
                print("未找到")  # 如果没有找到，则输出未找

        shop_name_index = shop_name_index[0]+1


        ##选择账号下的店铺名称
        self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div[2]/div/div[1]/div/div/div/div[{}]/div/div/div'.format(shop_name_index)).click()
        time.sleep(0.5)

        self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div[2]/div/div[2]/button').click()


        return life_account_id_list[0]

    def listen_shop_name_list_id(self):
        self.ch.refresh()
        # time.sleep(5)
        self.ch.listen.start('https://life.douyin.com/life/gate/v1/account/groupAccountList/')


        shop_name_index = []
        life_account_id_list = []
        shop_name = '上海明牌首饰有限公司'
        for packet in self.ch.listen.steps(timeout=20):
            account_list = packet.response.body["data"]["list"]
            print(account_list)
            for i in account_list:
                print(i)
                if shop_name == i["account_name"]:
                    print(i)
                    life_account_id_list.append(i["detail"]["life_account_id"])
        print(life_account_id_list[0])
        return life_account_id_list[0]

    def select_order_refer(self):
        time.sleep(3)
        cookies = self.get_cookies()
        headers = {"Cookie":cookies,
                   "referer":"https://life.douyin.com/p/liteapp/fulfillment-fusion/order?groupid=1765480014223375"}

        payload = {
            "filter": {
                # "start_time": 1728576000,
                # "end_time": 1729180799,
                "product_option": [],
                "order_id": "1071346892386583768",
                "is_market": False,
                "is_market_poi": False,

            },
            "is_user_poi_filter": False,
            "industry": "industry_common",
            "permission_common_param": {}
        }
        life_account_id_list = '7229227905112115233'
        url = 'https://life.douyin.com/life/trade_view/v1/sale/query/certificate_list/?page_index=1&page_size=20&industry=industry_common&root_life_account_id=%s'%life_account_id_list
        amount = requests.post(url,headers=headers,data=json.dumps(payload))
        amount_order = amount.json()["data"]["list"][0]
        #订单编号
        order_id = amount_order["order_id"]
        #订单状态{Status:1未核销 status:2已核销 status:4已退款}
        order_status = amount_order["status"]
        #订单标签
        order_tag_name = amount_order["order_tag"][0]["tag_name"]
        ##订单标签类型
        order_tag_type = amount_order["order_tag"][0]["tag_type"]
        #商品名称
        order_title = amount_order["sku"]["title"]
        #商品图片
        order_image = amount_order["sku"]["image"]
        ##sku ID
        order_sku_id = amount_order["sku"]["sku_id"]
        ##支付时间
        order_pay_time = amount_order["pay_time"]
        ##商品原价
        crossed_amount = amount_order["amount"]["crossed_amount"]
        crossed_amount = float(crossed_amount)/100

        ##售卖金额
        coupon_pay_amount = amount_order["amount"]['coupon_pay_amount']
        coupon_pay_amount = float(coupon_pay_amount)/100

        ##订单实收金额
        pay_amount = amount_order["amount"]['pay_amount']
        pay_amount = float(pay_amount)/100

        ##成交渠道
        sale_channel = amount_order["extra"]["attribute"]["sale_channel"]

        sale_user_nickname  = amount_order["extra"]["attribute"]["sale_user_nickname"]

        video_share_url = amount_order["extra"]["attribute"]["video_share_url"]
        print(video_share_url)
        if 'share/video' in video_share_url:
            video_share_id = video_share_url.split('https://www.iesdouyin.com/share/video/')[1]
            print(video_share_id)
        if 'webcast/reflow/' in video_share_url:
            video_share_id = video_share_url.split('https://webcast.amemv.com/webcast/reflow/')[1]
            print(video_share_id)
        if '//user/profile/' in video_share_url:
            print("存在")
            video_share_id = video_share_url.split('//user/profile/')[1]
            print(video_share_id)

        #带货角色
        sale_user_role = amount_order["extra"]["attribute"]["sale_user_role"]

        order_json = {"order_id":order_id,"order_status":order_status,"title":order_title,"image":order_image,"sku_id":order_sku_id,"pay_time":order_pay_time,
                      "crossed_amount":crossed_amount,"coupon_pay_amount":coupon_pay_amount,"pay_amount":pay_amount,"order_tag_name":order_tag_name,"order_tag_type":order_tag_type,
                      "sale_channel":sale_channel,"sale_user_role":sale_user_role,"sale_user_nickname":sale_user_nickname,"video_share_id":video_share_id}
        print(order_json)


    def get_tracks(self,distance):

        """滑块的运动轨迹"""
        value = round(random.uniform(0.55,0.75),2)
        v,t,sum1 = 0, 0.3,0
        plus = []
        mid = distance * value
        while sum1 < distance:
            if sum1 < mid:
                a = round(random.uniform(2.5,3.5),1)
            else:
                a = -round(random.uniform(2.0,3.0),1)
            s = v * t + 0.5 * a *(t ** 2 )
            v = v + a *t
            sum1+=s
            plus.append(round(s))
        return plus


    def slide_verification(self):
        ##获取滑块背景图片

        iframe = self.ch.get_frame('t:iframe')

        background_bytes = iframe.ele('xpath://*[@id="captcha_verify_image"]').src()

        # print(background_bytes)
        ##获取缺口图片
        cut_bytes = iframe.ele('xpath://*[@id="captcha-verify_img_slide"]').src()
        import ddddocr

        det = ddddocr.DdddOcr(det = False,ocr=False,show_ad=False)

        result = det.slide_match(cut_bytes,background_bytes,simple_target=True)
        print(result)
        offset = result["target"][0]
        tracks = self.get_tracks(offset)
        print("滑动轨迹",tracks)

        ##获取按键  按着不动
        iframe.actions.hold('xpath://*[@id="vc_captcha_box"]/div/div/div[4]/div/div[2]/div[2]/div')
        for track in tracks:
            iframe.actions.move(offset_x=track,offset_y=round(random.uniform(1.0,2.5),0),duration=.2)
        time.sleep(0.1)
        iframe.actions.release('xpath://*[@id="vc_captcha_box"]/div/div/div[4]/div/div[2]/div[2]/div')
            # ##输入验证码
            # self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div/div[3]/div[2]/div/form/div[2]/div/span/label/input').input('44444\n')
            #
            # ###点击授权同意框
            #
            # self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div/div[5]/span/span/label/span[1]').click()
            #
            # ##点击立即入住
            # self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div/div[3]/div[2]/div/form/div[3]/div/button').click()
        # else:
        # print('在这里')
        # print(self.listen_shop_name_list())
        # self.select_order_refer()




        # else:
        #
        #     self.redis_conn.set('dy_center_qrcode:{}'.format(self.user_id), '"no_login"')
        #     self.redis_conn.expire('dy_center_qrcode:{}'.format(self.user_id), 300)


    def dy_creator_center_spider(self):

        print('用户:',self.user_id, '此次的端口是:',self.PORT)

        self.ch.get('https://life.douyin.com/p/login')
        time.sleep(2)
        user_it_exist = self.user_state()
        data_frame = self.user_info()
        if user_it_exist == "用户不存在":
            data_frame["spider_login_code"] = '0'
            pd.io.sql.to_sql(data_frame, 'dy_life_center', self.mysql_config(), schema='data-warehouse',
                             if_exists='append', index=False)


        login_url_is = self.ch.url
        if login_url_is == "https://life.douyin.com/p/login":
            # self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div/div[3]/div[2]/div/form/div[1]/div/span/span[2]/label').input('18868750739\n')
            # time.sleep(0.5)



            time.sleep(180)
            # ###获取验证码
            # time.sleep(2)
            # self.ch.ele('xpath://*[@id="life_login_page"]/div[2]/div/div/div/div/div[3]/div[2]/div/form/div[2]/div/span/label/span/span').click()
            #
            # time.sleep(5)

        # self.select_order_refer()
        time.sleep(3)
        # print(self.listen_shop_name_list_id())
dy_center = DOUYIN_LIFE(user_id='trix-wang@email496c773a8e4741849220a988a39950ab')
aa = dy_center.dy_creator_center_spider()

